其他
如何写出让同事膜拜的漂亮代码?
点击上方“Python大本营”,选择“置顶公众号”
python大本营 IT人的职业提升平台
“代码千万行,注释第一行;编程不规范,同事两行泪”;"道路千万条,安全第一条。代码不规范,亲人两行泪。"在技术圈广为盛传,可见代码不规范让程序员们是多么的头痛。
重构改进软件的设计
重构使软件更容易理解
重构帮助找到bug
重构提高编程速度
预备性重构:让添加新功能更容易
帮助理解的重构:使代码更易懂
捡垃圾式重构
有计划的重构和见机行事的重构
长期重构
复审代码时重构
何时不应该重构
plays.json…
2 "hamlet": {"name": "Hamlet", "type": "tragedy"},
3 "as-like": {"name": "As You Like It", "type": "comedy"},
4 "othello": {"name": "Othello", "type": "tragedy"}
5}
invoices.json…
2 {
3 "customer": "BigCo",
4 "performances": [
5 {
6 "playID": "hamlet",
7 "audience": 55
8 },
9 {
10 "playID": "as-like",
11 "audience": 35
12 },
13 {
14 "playID": "othello",
15 "audience": 40
16 }
17 ]
18 }
19]
2 let totalAmount = 0;
3 let volumeCredits = 0;
4 let result = `Statement for ${invoice.customer}\n`;
5 const format = new Intl.NumberFormat("en-US",
6 { style: "currency", currency: "USD",
7 minimumFractionDigits: 2 }).format;
8 for (let perf of invoice.performances) {
9 const play = plays[perf.playID];
10 let thisAmount = 0;
11 switch (play.type) {
12 case "tragedy":
13 thisAmount = 40000;
14 if (perf.audience > 30) {
15 thisAmount += 1000 * (perf.audience - 30);
16 }
17 break;
18 case "comedy":
19 thisAmount = 30000;
20 if (perf.audience > 20) {
21 thisAmount += 10000 + 500 * (perf.audience - 20);
22 }
23 thisAmount += 300 * perf.audience;
24 break;
25 default:
26 throw new Error(`unknown type: ${play.type}`);
27 }
28 // add volume credits
29 volumeCredits += Math.max(perf.audience - 30, 0);
30 // add extra credit for every ten comedy attendees
31 if ("comedy" === play.type) volumeCredits += Math.floor(perf.audience / 5);
32 // print line for this order
33 result += ` ${play.name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
34 totalAmount += thisAmount;
35 }
36 result += `Amount owed is ${format(totalAmount/100)}\n`;
37 result += `You earned ${volumeCredits} credits\n`;
38 return result;
39}
invoices.json
和plays.json
)作为测试输入,运行这段代码,会得到如下输出:2 Hamlet: $650.00 (55 seats)
3 As You Like It: $580.00 (35 seats)
4 Othello: $500.00 (40 seats)
5Amount owed is $1,730.00
6You earned 47 credits
—— 推 荐 阅 读 ——